package lovely.gwt.jsonrpc.test.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rocket.util.server.InputOutput;

/**
 * This servlet simply echos the attribute value of params from post data from
 * the incoming request.
 * 
 * @author Stefan Martin
 */
public class EchoServlet extends HttpServlet {
	public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
		response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Only posts are supported.");
	}

	public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
		this.handleRequest(request, response);
	}

	final String RESPONSE_BEGIN = "{\"version\": \"1.1\",\"result\":\"";

	final String RESPONSE_END = "\"}";

	protected void handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
		BufferedReader reader = null;
		BufferedWriter writer = null;
		// encapsulate request as result string
		try {
			reader = new BufferedReader(request.getReader());
			writer = new BufferedWriter(response.getWriter());
			writer.write(RESPONSE_BEGIN);
			String line;
			while ((line = reader.readLine()) != null) {
				writer.write(line.replace("\"", "\\\""));
			}
			writer.write(RESPONSE_END);
		} finally {
			InputOutput.closeIfNecessary(reader);
			InputOutput.closeIfNecessary(writer);
		}
	}

}
